import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer, ConnectedSocket } from '@nestjs/websockets';
import { WebsocketService } from './websocket.service';
import { Server, Socket } from 'socket.io'
import { WsAuthDto } from './webscoket.dto';
import { UseGuards } from '@nestjs/common';
import { SocketJwtGuard } from './websocket.guard';

@WebSocketGateway({
	allowEIO3:true,
	cors:{
		origin:'*'
	}
})
@WebSocketGateway()
export class WebsocketGateway {
	constructor(private readonly websocketService: WebsocketService) {}

	@WebSocketServer() server: Server
	handleConnection(client: Socket) {
		this.server.on('connection', () => {
			// console.log('websocket:与服务器建立连接成功')
		})
	}

	@UseGuards(SocketJwtGuard) //使用jwt鉴权 createWebsocketDto.userId-自动解析用户id
	@SubscribeMessage('auth')
	async auth(@MessageBody() authDto: WsAuthDto,@ConnectedSocket() client: Socket) {
		return await this.websocketService.auth(this.server,authDto,client);
	}

	@SubscribeMessage('hello')
	hello() {
		return this.websocketService.hello();
	}

	@SubscribeMessage('removeWebsocket')
	remove(@MessageBody() id: string) {
		return this.websocketService.remove(id);
	}
}
